<template>
  <CDialog
    :title="title"
    v-model:visible="dialogVisible"
    :loading="loading"
    confirmText="保存"
    cancelText="关闭"
    size="small"
    @confirm="handleConfirm"
    @cancel="dialogVisible = false"
  >
    <el-form ref="formRef" :model="formState" :rules="rules" label-position="top">
      <el-row :gutter="0">
        <el-col :span="24">
          <el-form-item label="类型" prop="dataType">
            <el-select
              v-model="formState.dataType"
              placeholder="请选择"
              clearable
              @change="handleChangeDataType"
            >
              <el-option
                v-for="item in typeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="名称" prop="nodeName">
            <el-select
              v-model="formState.nodeName"
              :placeholder="!formState.dataType ? '请先选择类型' : '请选择'"
              clearable
              :disabled="!formState.dataType"
              @change="handleChangeName"
              v-if="isShowNameSelect"
            >
              <el-option
                v-for="unit in nameOptions"
                :key="unit.value"
                :label="unit.label"
                :value="unit.value"
              />
            </el-select>
            <el-input
              v-else
              v-model="formState.nodeName"
              :placeholder="!formState.dataType ? '请先选择类型' : '请输入'"
              clearable
              :disabled="!formState.dataType"
              maxlength="200"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="用量" prop="dosage">
            <CDosageAndUnit
              v-model:dosage="formState.dosage"
              v-model:unit="formState.unit"
              placeholder="请输入"
              :digit="9"
              is-group
            ></CDosageAndUnit>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注">
            <el-input v-model="formState.remark" type="textarea" placeholder="请输入" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </CDialog>
</template>

<script lang="ts" setup name="FlowDialog">
import { withDefaults, defineProps, defineEmits, computed, watch, reactive, ref } from 'vue';
import { CDialog } from '@/components/CDialog';
import CDosageAndUnit from '@/businessComponents/CDosageAndUnit/index.vue';
import type { ProcessDataItem } from '@/apis/pcf/myModel/model/modelDetailModel';
import { getSystemDict } from '@/apis/common/common';
import type { SystemDictResult } from '@/apis/common/model/commonModel';
import { useMessage } from '@/hooks/useMessage';
import { FlowDialogOperationType } from './flow-dialog';
import { rules } from './rules';
import { uniqWith, isEqual } from 'lodash';
import {
  getManufactureData,
  addManufactureData,
  editManufactureData
} from '@/apis/todo/flowBusiness';
import { ISupplierFormAttachment } from '@/apis/todo/model/flowBusinessModel';
interface INameCode {
  label: string;
  value: string;
  dataCode: string;
}
interface FlowDialogProps {
  visible: boolean;
  formNo: string;
  nodeNo: string;
  flowItem?: ProcessDataItem;
}
const props = withDefaults(defineProps<FlowDialogProps>(), {});
const emits = defineEmits(['update:visible', 'refresh']);
const { createMessage } = useMessage();
const dialogVisible = computed({
  get: () => {
    return props.visible;
  },
  set: (value: boolean) => {
    emits('update:visible', value);
  }
});
watch(
  () => dialogVisible.value,
  val => {
    if (val) {
      init();
    }
  }
);

const formRef = ref();
const loading = ref(false);

/**
 * 表单内容
 */
const formState = reactive({
  nodeNo: '',
  formNo: '',
  dataType: '',
  nodeName: '',
  dosage: '',
  unit: 'pcs',
  remark: '',
  supplierFormAttachmentList: [] as ISupplierFormAttachment[]
});

/**
 * 操作类型
 */
const operationType = ref<FlowDialogOperationType>();

/**
 * 弹窗标题
 */
const title = computed(() => {
  return operationType.value === 'ADD' ? '新增场地数据' : '编辑场地数据';
});

/**
 * 初始化
 */
function init() {
  loading.value = false;
  getTypeDict();
  if (!props.nodeNo) {
    operationType.value = 'ADD';
    formState.formNo = props.formNo;
    formState.nodeName = '';
    formState.dataType = '';
    formState.dosage = '';
    formState.unit = 'pcs';
    formState.remark = '';
  } else {
    operationType.value = 'EDIT';
    formState.nodeNo = props.nodeNo;
    getData(props.nodeNo);
  }
}

/**
 * 获取节点详情
 */
async function getData(nodeNo: string) {
  try {
    loading.value = true;
    const res = await getManufactureData(nodeNo);
    formState.nodeName = res.nodeName;
    formState.dataType = res.dataType;
    formState.supplierFormAttachmentList = res.supplierFormAttachmentList;
    getNameOptions();
    formState.dosage = res.dosage;
    formState.unit = res.unit;
    formState.remark = res.remark;
    loading.value = false;
  } catch (error) {
    console.log('error', error);
    loading.value = false;
  }
}

type TypeOptionsType = ({
  isShowNameSelect: boolean;
  // eslint-disable-next-line no-undef
} & LabelValueOptions[0])[];

const typeDictRes = ref<SystemDictResult[]>([]);
const typeOptions = ref<TypeOptionsType>([]);
const nameOptions = ref<INameCode[]>([]);
/**
 * 是否显示名称选择框
 */
const isShowNameSelect = ref(false);
/**
 * 获取类型和名称 字典
 */
async function getTypeDict() {
  try {
    const res = await getSystemDict('FLOW');
    typeDictRes.value = res || [];
    typeOptions.value = uniqWith(
      res.map(item => {
        return {
          label: item.dataDesc,
          value: item.dataGroup,
          isShowNameSelect: !!item.dataValue
        };
      }),
      isEqual
    );
  } catch (error) {
    console.log('error', error);
  }
}

function handleChangeDataType() {
  formState.nodeName = '';
  getNameOptions();
}

/**
 * 获取名称下拉选项
 */
function getNameOptions() {
  const item = typeOptions.value.find(item => item.value === formState.dataType);
  if (item && !item.isShowNameSelect) {
    isShowNameSelect.value = false;
    return;
  }
  isShowNameSelect.value = true;
  nameOptions.value = typeDictRes.value
    .filter(item => item.dataGroup === formState.dataType)
    .map(item => {
      return {
        label: item.dataValue,
        value: item.dataValue,
        dataCode: item.dataCode
      };
    });
}
const handleChangeName = (val: string) => {
  const index = nameOptions.value.findIndex(item => item.value == val);
  if (index > -1) {
    formState.unit = nameOptions.value[index].dataCode;
    setTimeout(() => {
      formRef.value?.clearValidate('dosage');
    });
  }
};

/**
 * 保存按钮
 */
function handleConfirm() {
  console.log('handleConfirm');
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      submitFlowReq();
    }
  });
}

/**
 * 接口请求
 */
async function submitFlowReq() {
  try {
    loading.value = true;
    if (operationType.value === 'ADD') {
      await addManufactureData(formState);
    } else {
      await editManufactureData(formState);
    }
    createMessage.success(operationType.value === 'ADD' ? '新增成功！' : '编辑成功！');
    emits('refresh');
    dialogVisible.value = false;
  } catch (error) {
    console.log('error', error);
    loading.value = false;
  }
}
</script>
